require 'nokogiri'
require 'tempfile'

class Tblock < ActiveRecord::Base
  belongs_to :article
  belongs_to :page
  has_one :nf_rect, :dependent => :destroy
  has_many :words, :dependent => :destroy

  accepts_nested_attributes_for:nf_rect, :allow_destroy => true

  def self.default_fxml_params
    { :include => :nf_rect }
  end

  SECTION_NAMES = [
                   "abstract.body",
                   "abstract.heading",
                   #"acknowledgements.body",
                   "acknowledgements.heading",
                   "affiliation",
                   "authors",
                   #"discussion.body",
                   "discussion.heading",
                   #"discussion.subheading",
                   "figure.legend",
                   #"footer",
                   #"header",
                   #"introduction.body",
                   "introduction.heading",
                   "junk",
                   "keywords",
                   "main.body",
                   "main.subheading",
                   #"methods.body",
                   "material_methods.heading",
                   #"material_methods.subheading",
                   "references.body",
                   "references.heading",
                   #"results.body",
                   "results.heading",
                   #"results.subheading",
                   "table.legend",
                   "title"
                  ]

  def modify_blocks_xml(attr_hash = {})
    # add class information to -blocks.xml file
    if self.classification or self.ml_class
      xml_filename = self.article.xml.original_filename
      xml_doc = Nokogiri::XML(open(self.article.xml.path))
      block_node = xml_doc.root.xpath("//Block[@id = '#{self.tbid}']").first
      block_node["class"] = (self.classification || self.ml_class)
      tfile = Tempfile.new(self.article.xml.path)
      tfile.puts xml_doc.to_xml
      # update model attachment with new xml file
      blocks_filename = self.article.xml_file_name
      self.article.xml = tfile
      self.article.xml.instance_write(:file_name, xml_filename)
      self.article.save
    end
  end

end
